#ifndef QUFILE_H
#define QUFILE_H

#include <QStringList>
#include <QFile>

// 涉及文件操作的一些辅助函数
class QuFile
{
public:

    static QStringList readLines(const QString& filePath, bool triming = true, bool ignoreEmptyLine = true);

    static bool writeLines(const QString& filePath, const QStringList& lines, bool append = false);

    // @line: 勿须包含回车符，函数会自动附加'\n'
    static bool appendLine(const QString& filePath, const QString& line);

    // @line: 勿须包含回车符，函数会自动附加'\n'
    static bool writeLine(QFile& file, const QString& line);

    template<int COLUMN>
    static QVector<std::array<QString, COLUMN>> readTextMatrix(const QString& filePath, const QChar sep = '\t') {
        auto lines = readLines(filePath, false); // NO TRIMING
        QVector<std::array<QString, COLUMN>> res;
        res.reserve(lines.size());
        for (auto& i : lines) {
            auto tokens = i.split(sep);
            if (tokens.size() != COLUMN)
                continue;

            std::array<QString, COLUMN> ele;
            for (int n = 0; n < COLUMN; n++)
                ele[n] = tokens[n];
            res.emplaceBack(std::move(ele));
        }

        return res;
    }

    template<int COLUMN>
    static bool writeTextMatrix(const QVector<std::array<QString, COLUMN>>& mat, const QString& filePath, const QChar sep = '\t') {
        QFile f(filePath);
        if (!f.open(QFile::WriteOnly | QFile::Text))
            return false;

        for (auto& i : mat) {
            QString line(i[0]);
            for (int j = 1; j < COLUMN; j++)
                line += '\t', line += i[j];
            if (!writeLine(f, line)) return false;
        }

        return true;
    }

private:
    QuFile() = default;
};

#endif // QUFILE_H
